package cn.itsource.hrm.asserts;


import cn.itsource.hrm.exception.ErrorEnum;
import cn.itsource.hrm.exception.GlobalException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 参数断言工具
 */
public class ParamAssertUtils {

    public static String emailRegex = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    public static String phoneRegex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";

    /**
     * 非空断言
     * @param obj
     * @param code
     */
    public static void assertNotEmpty(Object obj, ErrorEnum code){
        if(obj == null){
            throw new RuntimeException(code.getMsg());
        }
        if(obj instanceof String){
            String objStr = (String) obj;
            if(objStr.trim().length() == 0 ){
                throw new GlobalException(code);
            }
        }
    }

    /**
     * 已存在断言
     * @param obj
     * @param code
     */
    public static void assertISExist(Object obj,ErrorEnum code){
        if(obj != null){
            throw new GlobalException(code);
        }

    }


    /**
     * 邮箱的验证
     * @param email
     */
    public static void assertIsEmail(String email){
        assertNotEmpty(email,ErrorEnum.NOT_EMPTY.setMsg("邮箱"));
        Pattern p = Pattern.compile(emailRegex);
        Matcher m = p.matcher(email);
        if(!m.matches()){
            throw new GlobalException(ErrorEnum.IS_NOT_MATCH.setMsg("邮箱"));
        };
    }

    /**
     * 手机号的验证
     * @param phone
     */
    public static void assertIsPhone(String phone){
        assertNotEmpty(phone,ErrorEnum.NOT_EMPTY.setMsg("手机号不能为空!"));
        Pattern p = Pattern.compile(phoneRegex);
        Matcher m = p.matcher(phone);
        if(!m.matches()){
            throw new GlobalException(ErrorEnum.IS_NOT_MATCH.setMsg("手机"));
        };
    }

    public static void main(String[] args){
        String str = "AAA%sBBB";
        System.out.println(String.format(str, "xxx"));
    }
}